package com.picrepo.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.picrepo.app.AppData;
import com.picrepo.task.UploadTask;
import com.picrepo.task.UploadTask.OnUploadListerner;
import com.picrepo.util.PicUtil;

/**
 * This activity is used to take photo and uplaod.
 */
public class UploadActivity extends Activity implements 
	OnClickListener, OnUploadListerner
{
	private static final String TAG = UploadActivity.class.getSimpleName();
	private static final int REQUEST_TAKE_PHOTO = 0x1;
	private String mCurrentPhotoPath;
	private String mUsername;
	
	private ImageView mImagePreview;
	private BootstrapButton mButtonTake;
	private BootstrapButton mButtonRetake;
	private BootstrapButton mButtonUplaod;
	private LinearLayout mLayout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		setupView();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_TAKE_PHOTO && 
				resultCode == Activity.RESULT_OK && data != null) {
			mButtonTake.setVisibility(View.INVISIBLE);
			mLayout.setVisibility(View.VISIBLE);
			
			Uri uri = data.getData();
			Cursor cursor = this.getContentResolver()
					.query(uri, null, null, null, null);
			cursor.moveToFirst();
			mCurrentPhotoPath = cursor.getString(
					cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
			
			if (Build.VERSION.SDK_INT < 14) {    
                cursor.close();    
            }    
			
			mImagePreview.setImageBitmap(PicUtil.getSmallBitmap(mCurrentPhotoPath));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.upload_button_take_photo:
		case R.id.upload_button_retake_photo:
			takePhoto();
			break;
		
		case R.id.upload_button_upload:
			Toast.makeText(UploadActivity.this, "图片上传中...", 
					Toast.LENGTH_LONG).show();
			UploadTask uploadTask = new UploadTask();
			uploadTask.execute(mUsername, mCurrentPhotoPath);
			uploadTask.setOnUploadListerner(this);
			break;

		default:
			break;
		}
	}

	@Override
	public void onSuccess(String result) {
		int code = AppData.UPLOAD_ERROR;
		
		try {
			JSONObject json = new JSONObject(result);
			code = json.getInt("code");
		} catch (JSONException e) {
			Log.d(TAG, "upload: " + e.getMessage());
			e.printStackTrace();
		}
		
		if (code == AppData.UPLOAD_ERROR) {
			Toast.makeText(UploadActivity.this, "上传失败, 请重新上传", 
					Toast.LENGTH_LONG).show();
		} else if (code == AppData.UPLOAD_OK) {
			Toast.makeText(UploadActivity.this, "上传成功~", 
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onFailure() {
		Toast.makeText(UploadActivity.this, "上传失败, 请重新上传", 
				Toast.LENGTH_LONG).show();
	}
	
	/**
	 * Setup all the view in this activity.
	 */
	private void setupView() {
		mUsername = getIntent().getStringExtra("username");
		if (mUsername == null || mUsername.equals("")) {
			SharedPreferences userInfo = getSharedPreferences("user_info", MODE_PRIVATE);
			mUsername = userInfo.getString("account", "");
		}
		
		mImagePreview = (ImageView) findViewById(R.id.upload_image_preview);
		mButtonTake = (BootstrapButton) findViewById(R.id.upload_button_take_photo);
		mButtonRetake = (BootstrapButton) findViewById(R.id.upload_button_retake_photo);
		mButtonUplaod = (BootstrapButton) findViewById(R.id.upload_button_upload);
		mLayout = (LinearLayout) findViewById(R.id.upload_layout_retake_upload);
		
		mButtonTake.setOnClickListener(this);
		mButtonRetake.setOnClickListener(this);
		mButtonUplaod.setOnClickListener(this);
	}

	/**
	 * Take photo.
	 */
	private void takePhoto() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
	}
}
